<script setup lang="ts">
import { ref, computed, nextTick, onMounted, watch } from 'vue'
import { useAIStore } from '@/store/aiStore'
import { sendAIRequest } from '@/utils/aiService'

const aiStore = useAIStore()
const {
  chatHistory,
  userInput,
  isLoading,
  currentAIModel,
  aiModels,
  addMessage,
  clearHistory: storeClearHistory
} = aiStore

const messagesContainer = ref(null)
const inputField = ref(null)

const currentModel = computed(() => {
  return aiModels.value.find(model => model.id === currentAIModel.value) || aiModels.value[0]
})

const formatMessage = (content) => {
  // 简单的Markdown格式化，实际项目可使用专门的库
  return content
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      .replace(/`(.*?)`/g, '<code>$1</code>')
      .replace(/\n/g, '<br/>')
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const handleKeyDown = (e) => {
  if (e.shiftKey) {
    // 允许使用Shift+Enter换行
    return
  }
  sendMessage()
}

const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  const userMessage = {
    role: 'user',
    content: userInput.value.trim()
  }

  addMessage(userMessage)
  userInput.value = ''
  isLoading.value = true

  try {
    // 添加一个空的AI回复占位符
    const placeholderMessage = {
      role: 'assistant',
      content: ''
    }
    addMessage(placeholderMessage)

    // 滚动到底部
    scrollToBottom()

    // 发送请求到后端
    const response = await sendAIRequest(
        currentAIModel.value,
        [...chatHistory.value.slice(0, -1), userMessage]
    )

    // 更新最后一条消息（AI回复）
    if (chatHistory.value.length > 0) {
      chatHistory.value[chatHistory.value.length - 1] = {
        role: 'assistant',
        content: response
      }
    }
  } catch (error) {
    console.error('AI请求失败:', error)
    if (chatHistory.value.length > 0) {
      chatHistory.value[chatHistory.value.length - 1] = {
        role: 'assistant',
        content: '抱歉，我暂时无法回答这个问题。请稍后再试或换一个问题。'
      }
    }
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

const quickAsk = (question) => {
  userInput.value = question
  nextTick(() => {
    if (inputField.value) {
      inputField.value.focus()
    }
  })
}

const clearHistory = () => {
  if (chatHistory.value.length > 0) {
    if (confirm('确定要清空对话历史吗？')) {
      storeClearHistory()
    }
  }
}

// 自动滚动到底部
watch(chatHistory, () => {
  scrollToBottom()
})

onMounted(() => {
  scrollToBottom()
})
</script>

<template>
  <div class="chat-interface">
    <div class="chat-header">
      <h3>{{ currentModel.name }} 助手</h3>
      <button @click="clearHistory" class="clear-btn" title="清空对话">
        <i class="icon-clear"></i>
      </button>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div
          v-for="(message, index) in chatHistory"
          :key="index"
          class="message"
          :class="message.role"
      >
        <div class="message-content">
          <div v-if="message.role === 'assistant'" class="model-indicator">
            <span :class="`model-icon ${currentAIModel}`"></span>
          </div>
          <div class="message-text">
            <template v-if="message.role === 'assistant' && index === chatHistory.length - 1 && isLoading">
              <span class="thinking-animation">思考中...</span>
            </template>
            <template v-else>
              <div v-html="formatMessage(message.content)"></div>
            </template>
          </div>
        </div>
      </div>

      <div v-if="chatHistory.length === 0" class="welcome-message">
        <h4>你好！我是你的AI助手</h4>
        <p>选择左侧的AI模型，我可以帮你解答问题、提供思路或辅助工作。</p>
        <div class="quick-tips">
          <span>试试问：</span>
          <button @click="quickAsk('如何提高前端性能？')">如何提高前端性能？</button>
          <button @click="quickAsk('解释Vue3的响应式原理')">解释Vue3原理</button>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <textarea
          v-model="userInput"
          @keydown.enter.exact.prevent="handleKeyDown"
          placeholder="输入你的问题，按Enter发送..."
          ref="inputField"
      ></textarea>
      <button @click="sendMessage" :disabled="isLoading">
        <i class="icon-send" :class="{ 'sending': isLoading }"></i>
      </button>
    </div>
  </div>
</template>

<style scoped>

</style>